var myScroll = []; 
var windowHeight = $(window).height();
var windowWidth = $(window).width();
var babyGender = 0;

var nsUserInfo = {
	userId : 0,
	userGender : 0,
	userEmail : '',
	userPw : '',
};

$(document).delegate('[data-role="page"]', 'pageshow', function () {  
    var $page = $(this); 
	var pageId = $page.attr("id");

	initIscroll( $page );

	if( pageId == "pageUserLogin"){
		initPageUserLogin();
	}
	else if( pageId == "pageUserJoin"){
		initPageUserJoin();
	}
	else if( pageId == "pageUserReady" ){
		initPageUserReady();
	}
	else if( pageId == "pageCreateAga" ){
		initPageCreateAga();
	}
	else if( pageId == "pageInviteParent" ){
		initPageInviteParent();
	}
	else if( pageId == "pageRequestFamily" ){
		initPageRequestFamily();
	}

	for (x in myScroll) 
            myScroll[x].refresh(); 
}); 

$(document).delegate('[data-role="page"]', 'pagehide', function () { 
    // unset and delete iScroll 
    for (x in myScroll) 
    { 
        myScroll[x].destroy(); 
        myScroll[x] = null; 
        myScroll.splice(x, 1); 
    }
});

function initIscroll( page )
{
	$(page.find('.wrapper')).each( function(index) { 
        var scroller_id = $(this).get(0);
 
        myScroll.push ( 
       		 new iScroll(scroller_id, {
       				onBeforeScrollStart: function (e) {
       					var target = e.target;
        					while (target.nodeType != 1) target = target.parentNode;
       					
       					if( target.tagName != 'SELECT' && target.tagName != 'INPUT' && target.tagName != 'TEXTAREA' )
       						e.preventDefault();
       				}
       			}
	       	 )
        );
    }); 
}

function initPageUserLogin()
{
	$("#user_bg").css("height",windowHeight );
	$("#header").html("로그인<p id='btnHeaderJoin' class='btnHeaderJoin btnHeaderRight'></p>");
	new Quickly('btnHeaderJoin', function(e){
		$.mobile.changePage("user_join.html", {transition : 'slide'});
	});
	new Quickly('btnLogin', function(e){
		checkLogin();
	});
}

function initPageUserJoin()
{
	$("#header").html("<p id='btnBack' class='btnHeaderLeft btnHeaderBack'></p>회원가입");
	$("#user_join_bg").css("height",windowHeight);

	new Quickly('btnBack', function(e){
		$.mobile.changePage("user_login.html", {transition : 'none'});
	});
	new Quickly('join_man', function(e){
		$("#join_man").css("background-image","url(../images/user/btn_male_on.png)");
		$("#join_woman").css("background-image","url(../images/user/btn_female.png)");
		nsUserInfo.userGender=1;
	});
	new Quickly('join_woman', function(e){
		$("#join_man").css("background-image","url(../images/user/btn_male.png)");
		$("#join_woman").css("background-image","url(../images/user/btn_female_on.png)");
		nsUserInfo.userGender=2;
	});
	new Quickly('btnJoin', function(e){
		checkJoin();
	});
}

function initPageUserReady()
{
	$("#header").html("<p id='btnBack' class='btnHeaderLeft btnHeaderBack'></p>회원가입");
	$("#user_ready_bg").css("height", windowHeight);

	new Quickly('btnBack', function(e){
		$.mobile.changePage("user_login.html", {transition : 'none'});
	});
	new Quickly('btnInviteFamily', function(e){
		$.mobile.changePage("user_requestfamily.html", {transition : 'slide'});	
	});
	new Quickly('btnCreateAga', function(e){
		$.mobile.changePage("user_createroom.html", {transition : 'slide'});	
	});
}

function initPageCreateAga()
{
	$("#header").html("<p id='btnBack' class='btnHeaderLeft btnHeaderBack'></p>아가방 만들기");
	$("#btnPhotoProfile").css("left", (windowWidth/2 - 39)+"px" );
	$("#btnPhotoProfile").css("visibility","visible");
	$("#user_join_bg").css("height",$(window).height()+100);

	new Quickly('btnBack', function(e){
		$.mobile.changePage("user_ready.html", {transition : 'none'});
	});
	new Quickly('aga_profile_frame', function(e){
		selectPicture( "btnPhotoProfile" );
	});
	new Quickly('btnCreateAga2', function(e){
		checkCreateRoom();
		CreateRoomToServer( 'btnPhotoProfile', nsUserInfo.userId, 0, $.trim($("#babyName").val()), $.trim($("#babyNick").val()), $("#babyBirthday").val(), babyGender );
	});
	new Quickly('join_man', function(e){
		$("#join_man").css("background-image","url(../images/user/btn_male_on.png)");
		$("#join_woman").css("background-image","url(../images/user/btn_female.png)");
		babyGender=1;
	});
	new Quickly('join_woman', function(e){
		$("#join_man").css("background-image","url(../images/user/btn_male.png)");
		$("#join_woman").css("background-image","url(../images/user/btn_female_on.png)");
		babyGender=2;
	});
	new Quickly('show', function(e){
		$('#babyBirthday').scroller('show'); 
	});

    $('#babyBirthday').scroller({
        preset: 'date',
        minDate: new Date(2010, 1, 1),
        theme: 'default',
        display: 'modal',
        mode: 'mixed'
    });
}
function initPageInviteParent()
{
	$("#header").html("<p id='btnBack' class='btnHeaderLeft btnHeaderBack'></p>가족 초대");
	$("#user_invite_bg").css("height",$(window).height()+100);

	new Quickly('btnBack', function(e){
		location.href("../agailgi/main_aga.html");
	});
	new Quickly('btnInviteParent', function(e){
		inviteParent();
	});
	
	var userinfo = JSON.parse(localStorage.getItem("userInfo"));
	var genderText;
	if ( userinfo.gender == "1")
		genderText = "엄마";
	else if( userinfo.gender == "2" )
		genderText = "아빠";

	$("#invite_text").html(genderText+"를 추가해주세요");
}

function initPageRequestFamily()
{
	$("#header").html("가족 되기<p id='btnClose' class='btnHeaderRight btnHeaderClose'></p>");
	$("#scroller").css("height",$(window).height()+100);

	new Quickly('btnClose', function(e){
		$.mobile.changePage("user_ready.html", {transition : 'none'});
	});
	
	new Quickly('btnSearch', function(e){
		if( $("#babyNick").val() != "" ){
			searchBabyToServer( localStorage.getItem("userId"), $("#babyNick").val() );
		}
	});
}

function checkLogin(){
	if( $.trim($("#userEmail").val()) == '' ){
		alert("아이디를 입력해 주세요.");
        $("#userid").focus();
        return;
    }
    if( $.trim($("#userPw").val()) == '' ){
        alert("비밀번호를 입력해 주세요.");
        $("#userpwd").focus();
        return;
    }
	
	// 로그인 프로세스 호출
	loginToServer( $.trim($("#userEmail").val()), $.trim($("#userPw").val()) );
}

function checkJoin() {
	
	re = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;

	if( $.trim($("#joinUserEmail").val()).length < 6 || !re.test($.trim($("#joinUserEmail").val())) )
	{
		alert("이메일 형식이 맞지 않습니다.");
		return;
	}
	if ($.trim($("#joinUserEmail").val()) == '') {
		alert("이메일을 입력해 주세요.");
		$("#userId").focus();
		return;
	}
	if ($.trim($("#joinUserPw").val()) == '') {
		alert("패스워드를 입력해 주세요.");
		$("#userPw").focus();
		return;
	}
	if ($.trim($("#joinUserName").val()) == '') {
		alert("이름을 입력해 주세요.");
		$("#userName").focus();
		return;
	}

	if (nsUserInfo.userGender == 0) {
		alert("성별을 선택해 주세요.");
		return;
	}

	// 회원가입 프로세스 호출
	joinToServer( $("#joinUserEmail").val(), $('#joinUserPw').val(), $('#joinUserName').val(), nsUserInfo.userGender );
}

function checkCreateRoom(){
	if( $.trim($("#babyName").val()) == '' ){
		alert("아기 이름을 입력해 주세요.");
        $("#babyName").focus();
        return;
    }
    if( $.trim($("#babyNick").val()) == '' ){
        alert("아기 별명을 입력해 주세요.");
        $("#babyNick").focus();
        return;
    }
    if( $.trim($("#babyBirthday").val()) == '' ){
    	alert("아기 생일을 입력해 주세요.");
        return;
    }
	if (babyGender == 0) {
		alert("성별을 선택해 주세요.");
		return;
	}
}

// 새롭게 만들어진 아기의 정보를 로컬에 저장하기 위한 함수
function checkBaby( new_babyinfo )
{
	var userinfo = JSON.parse(localStorage.getItem("userInfo"));
	
	if( userinfo.num_of_baby == 0 )
	{
		new_babyinfo.name = $("#babyName").val();
		new_babyinfo.nick = $("#babyNick").val();
		
		localStorage.setItem("babyInfo", JSON.stringify(new_babyinfo) );
		localStorage.setItem("mainbaby_info", JSON.stringify(new_babyinfo) );
		
		userinfo.num_of_baby = 1;
		userinfo.mainbabyid = new_babyinfo.babyid;

		localStorage.setItem("userInfo", JSON.stringify(userinfo));
		
		$.mobile.changePage("user_inviteparent.html", {transition : 'slide'});
	}
	else if( userinfo.num_of_baby > 0 )
	{
		userinfo.num_of_baby += 1;
		userinfo.mainbabyid = new_babyinfo.babyid;
		localStorage.setItem("userInfo", JSON.stringify(userinfo));

		babies = JSON.parse( localStorage.getItem("babyInfo"));
		
		new_babyinfo.name = $("#babyName").val();
		new_babyinfo.nick = $("#babyNick").val();
		babies.push( new_babyinfo );

		localStorage.setItem("babyInfo", JSON.stringify(babies) );
		
		location.href ="../agailgi/main_aga.html";
	}
}

function inviteParent(){
	re = /^[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_.]?[0-9a-zA-Z])*.[a-zA-Z]{2,3}$/i;

	if( $.trim($("#invite_userId").val()).length < 6 || !re.test($.trim($("#invite_userId").val())) ){
		alert("이메일 형식이 맞지 않습니다.");
		return;
	}	
	
	var mainbaby_info = JSON.parse( localStorage.getItem("mainbaby_info") );
	
	inviteParentToServer( $.trim( $("#invite_userId").val() ), mainbaby_info.babyid );
}

function refreshBabyList( friendList, start )
{
	$("#requestFamily").html("");
	$.each( friendList, function(i, item){
		var temp = "<li>"
				+ "<div class='list_li'>"
				+ "<div id='list_frame_bg"+(start+i)+"' class='list_frame_bg'>"
				+ "<img id='list_gender"+(start+i)+"' class='list_gender' src='../images/profile/gender_male.png'>"
				+ "<p id='list_nick"+(start+i)+"' class='list_nick'>"+item.nick+"</p>"
				+ "<p id='list_babybirthday"+(start+i)+"' class='list_babybirthday'>생일 "+item.birthday.substr(0,10)+"</p>"
				+ "<p id='list_babyfrombirth"+(start+i)+"' class='list_babyfrombirth'>태어난지 "+countDay(item.birthday)+"일 되는 날</p>"
				+ "<p id='list_btn_invite' class='list_btn_invite'></p>"
				+ "<input id='searchBabyId"+(start+i)+"' style='display:none;' value='"+item.babyid+"'>"
				+ "</div></div></li>";
		
		$("#requestFamily").append(temp);
		$("#list_frame_bg"+(start+i)).css("background-image", "url('../images/list/sum_middle_baby.png'), "+ urlProfilePhoto(item.babyid, item.pf_name,"medium"));		
		$("#list_gender"+(start+i)).attr("src",checkGender(1, item.gender));
	});
	
	var temp = "<p class='list_bottom'>";
	$("#requestFamily").append(temp);

	$("#requestFamily #list_btn_invite").click(function(){
		var idx = $(".list_btn_invite").index($(this));

		requestFamilyToServer( localStorage.getItem('userId'), $("#searchBabyId"+idx).val(), idx );
	})
}

function myDateFormat( tempDate )
{
	console.log( tempDate );
	var tempArray = tempDate.split('-');
	
	//console.log( itemTimeArray[1] + "\/" + itemTimeArray[2] + "\/" + itemTimeArray[0] );
	return new Date( tempArray[0], tempArray[1], tempArray[2] );
}

$(document).ready(function()
{
	$("#userEmail").val( localStorage.getItem("userEmail") );
	$("#userPw").val( localStorage.getItem("userPw") );

	if (navigator.userAgent.indexOf("Android") != -1)
	{
		$.mobile.defaultPageTransition = 'none';
		$.mobile.defaultDialogTransition = 'none';
	}
	
	var loading = $('<img alt="loading" src="../css/images/ajax-loader.gif" />').appendTo(document.body).hide();
	
	$(window).ajaxStart(loading.show);
	$(window).ajaxStop(loading.hide);
})

document.addEventListener('touchmove', function (e) { e.preventDefault(); }, false);